import React from 'react';
import styles from './tag-list.scss';
import {Menu, Icon, Modal, Form, Input, message} from 'antd';
import actions from 'store/actions/img-repo';
const FormItem = Form.Item;
class TagList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false
    };
  }

  add() {
    this.setState({
      visible: true
    });
  }

  async handleOk() {
    const {dispatch} = this.props;
    const tag = this.props.form.getFieldValue('tag');
    if (!tag) {
      message.error('请输入分组名');
      return;
    }
    await dispatch(actions.addImgTags(tag));
    this.setState({
      visible: false
    });
  }

  handleCancel() {
    this.setState({
      visible: false
    });
  }

  async switchTag(tagId) {
    const {dispatch} = this.props;
    dispatch(actions.setCurrTag(tagId));
    await dispatch(actions.queryImgsByTag(tagId));
    dispatch(actions.setImgRepoPage(1));
  }

  buildMenu() {
    const {tags} = this.props;
    const dataSource = [{name: '全部图片', id: 'all'}, {name: '未分组', id: '-1'}].concat(tags);
    const result = [];
    for (let i = 0; i < dataSource.length; i++) {
      const item = dataSource[i];
      result.push(
        <Menu.Item
          key={item.id}
          onClick={() => {
            this.switchTag(item.id);
          }}
        >
          <span>{item.name}</span>
        </Menu.Item>
      );
    }
    result.push(
      <Menu.Item
        key={'add'}
        onClick={() => {
          this.add();
        }}
      >
        <Icon type="plus-circle" theme="outlined" />
        <span>添加分组</span>
      </Menu.Item>
    );
    return result;
  }

  render() {
    const getFieldDecorator = this.props.form.getFieldDecorator;
    return (
      <Menu defaultSelectedKeys={['all']}>
        {this.buildMenu()}
        <Modal
          title="添加分组"
          visible={this.state.visible}
          onOk={() => {
            this.handleOk();
          }}
          onCancel={() => {
            this.handleCancel();
          }}
          width={300}
        >
          <FormItem>
            {getFieldDecorator('tag', {
              rules: [{required: true, message: 'Please input your tagName!'}]
            })(<Input prefix={<Icon type="edit" theme="outlined" />} placeholder="请输入分组名" />)}
          </FormItem>
        </Modal>
      </Menu>
    );
  }
}

TagList = Form.create()(TagList);

export default TagList;
